'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateOauthClientApiByApiId } from '@/services/api';
import diff from 'microdiff';
import type { IDifference, IOauthClientApi } from '@/interfaces';
import type { TOauthClientApiType } from '@/types';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import Box from '@/app/[locale]/admin/common/box';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateOauthClientApiInfo(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IOauthClientApi;
    translatedFields: PrefixedTTranslatedFields<'oauthClientApiAdminPage'>;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    type: TOauthClientApiType;
    name: string;
    overview?: string;
    category?: string;
    doc?: string;
    upperLimit?: number;
  }>({
    type: source.type,
    name: source.name,
    overview: source.overview ?? '',
    category: source.category ?? '',
    doc: source.doc ?? '',
    upperLimit: source.upperLimit,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateOauthClientApiByApiIdMutation = useMutation(
    updateOauthClientApiByApiId,
  );

  useEffect(() => {
    const diffData = diff(
      {
        type: source.type,
        name: source.name,
        overview: source.overview ?? '',
        category: source.category ?? '',
        doc: source.doc ?? '',
        upperLimit: source.upperLimit,
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);

      const id = source.id;
      await updateOauthClientApiByApiIdMutation.mutateAsync({
        id,
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateOauthClientApiByApiIdMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(
    e: ChangeEvent<HTMLSelectElement | HTMLInputElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.properties.name}
          </label>
          <input
            type="text"
            name="name"
            value={form.name}
            onChange={onChangeForm}
            className="form-control"
            aria-label="name"
            placeholder={translatedFields.tip.name}
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.overview}
          </label>
          <input
            type="text"
            name="overview"
            value={form.overview}
            onChange={onChangeForm}
            className="form-control"
            aria-label="overview"
            placeholder={translatedFields.tip.overview}
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.category}
          </label>
          <input
            type="text"
            name="category"
            value={form.category}
            onChange={onChangeForm}
            className="form-control"
            aria-label="category"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.doc}
          </label>
          <textarea
            rows={1}
            name="doc"
            value={form.doc}
            onChange={onChangeForm}
            className="form-control"
            aria-label="doc"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.type}
          </label>
          <select
            name="type"
            value={form.type}
            onChange={onChangeForm}
            className="form-select"
            aria-label="type"
          >
            {['DEFAULT', 'REQUIRED'].map((key) => {
              return (
                <option key={key} value={key}>
                  {(translatedFields as any).enums.type[key]}
                </option>
              );
            })}
          </select>
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.upperLimit}
          </label>
          <input
            min={0}
            type="number"
            name="upperLimit"
            value={form.upperLimit}
            onChange={onChangeForm}
            className="form-control"
            aria-label="upperLimit"
            placeholder={translatedFields.tip.upperLimit}
          />
        </div>

        <button
          type="submit"
          disabled={
            updateOauthClientApiByApiIdMutation.isLoading || isDisabledSave
          }
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateOauthClientApiByApiIdMutation.isLoading && (
            <Spinner classs="me-2" />
          )}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
